package com.yune.activity.main.ui.find;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.yune.R;
import com.yune.activity.App;
import com.yune.adapter.SongListAdapter;
import com.yune.bean.SongBean;
import com.yune.utils.Network;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class FindFragment extends Fragment {
    private FindViewModel findViewModel;
    private SongListAdapter songListAdapter;//加载歌曲列表的适配器
    private final List<SongBean> data=new ArrayList<>();//ArrayList<>()构造一个初始容量为10的空列表。
    private TextView tip;
    private View root;
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (root==null) {
            root = inflater.inflate(R.layout.frgament_find, container, false);//container容器
            findViewModel = new ViewModelProvider(this).get(FindViewModel.class);//Provider供应者
            ListView list = root.findViewById(R.id.find_list);
            tip = root.findViewById(R.id.find_tip);
            songListAdapter = new SongListAdapter(getContext(), data);
            list.setAdapter(songListAdapter);
            list.setOnItemClickListener((parent, view, position, id) -> {//ItemClickListener项目单击监听器
                SongBean item = data.get(position);
                //判断性加入歌曲表song，require要求，runOnUiThread运行超线程
                findViewModel.addSong(item, songId -> requireActivity().runOnUiThread(() -> {
                    data.get(position).ifAddedOid = songId;
                    songListAdapter.notifyDataSetChanged();//notify通知Data数据SetChanged设置更新
                    sendNewPlayBroadcast(getActivity(), item);//发送新播放广播
                }));
            });
        }
        //getArguments获取参数，Arguments论据
        if (getArguments() != null && getArguments().getString("kw") != null) {
            String kw = getArguments().getString("kw");
            SharedPreferences.Editor editor = App.sp.edit();
            editor.putString("lastSearch", kw);
            editor.apply();
                //autumn秋天，fish鱼                                         Encoder编码器         Callback回拨
            Network.callApi("https://autumnfish.cn/cloudsearch?keywords=" + URLEncoder.encode(kw), new Callback() {
                @Override
                //Failure失败
                public void onFailure(@NotNull Call call, @NotNull IOException e) { }
                @Override
                //Response回应
                public void onResponse(@NotNull Call call, @NotNull Response response) {
                    //require要求
                    requireActivity().runOnUiThread(() -> {
                        try {
                            JSONArray jsonArray = new JSONObject(response.body().string()).getJSONObject("result").getJSONArray("songs");
                            songListAdapter.clear();
                            for (int j = 0; j < jsonArray.length(); j++) {
                                JSONObject jsonObject1 = (JSONObject) jsonArray.get(j);
                                SongBean adpSongBean = new SongBean(jsonObject1.getString("name"), jsonObject1.getJSONArray("ar").getJSONObject(0).getString("name"), jsonObject1.getJSONObject("al").getString("picUrl"), jsonObject1.getString("id"), "", true, "");
                                data.add(adpSongBean);
                            }
                            tip.setText("");
                            songListAdapter.notifyDataSetChanged();//notify通知Data数据SetChanged设置更新
                        } catch (JSONException | IOException e) {
                            e.printStackTrace();
                        }
                    });

                }
            });
        } else {//不是搜索而来就判断上次的
            if (!App.sp.getString("lastSearch", "null").equals("null")) {
                Network.callApi("https://autumnfish.cn/cloudsearch?keywords=" + URLEncoder.encode(App.sp.getString("lastSearch", "null")), new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    }
                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) {
                        requireActivity().runOnUiThread(() -> {
                            try {
                                JSONArray jsonArray = new JSONObject(response.body().string()).getJSONObject("result").getJSONArray("songs");
                                songListAdapter.clear();
                                for (int j = 0; j < jsonArray.length(); j++) {
                                    JSONObject jsonObject1 = (JSONObject) jsonArray.get(j);
                                    SongBean adpSongBean = new SongBean(jsonObject1.getString("name"), jsonObject1.getJSONArray("ar").getJSONObject(0).getString("name"), jsonObject1.getJSONObject("al").getString("picUrl"), jsonObject1.getString("id"), "", true, "");
                                    data.add(adpSongBean);
                                }
                                tip.setText("");
                                songListAdapter.notifyDataSetChanged();
                            } catch (JSONException | IOException e) {
                                e.printStackTrace();
                            }
                        });
                    }
                });
            }
        }
        return root;
    }
    //给服务发送播放歌曲的广播
    private void sendNewPlayBroadcast(Context context, SongBean item) {
        Intent intent = new Intent();
        intent.setAction("serviceReceiver");
        intent.putExtra("cmd","newPlay");
        intent.putExtra("songUrl",item.songUrl);
        intent.putExtra("songName",item.songName);
        intent.putExtra("singer",item.singer);
        intent.putExtra("picture",item.picture);
        intent.putExtra("songId",item.songId);
        intent.putExtra("fromWeb",item.fromWeb);
        intent.putExtra("ifAddedOid",item.ifAddedOid);
        context.sendBroadcast(intent);
    }
}